#!/usr/bin/env python3
#############################################################################
# trace2trace <inputfile> <outputfile>
#
# Converts a simulator trace file to the epiphany trace format
#
# Formats: spike, cgen
#
#############################################################################
import re
import sys

simulator="spike"
offset=0xffffffff00000000

#Input Arguments
with open(sys.argv[1], 'r') as f:
    file_content = f.read()

fileout=open(sys.argv[2],"w")

#RISC-V ABI dictionary
regs={
    "zero":"r0",
    "ra":"r1",
    "sp":"r2",
    "gp":"r3",
    "tp":"r4",
    "t0":"r5",
    "t1":"r6",
    "t2":"r7",
    "s0":"r8",
    "s1":"r9",
    "a0":"r10",
    "a1":"r11",
    "a2":"r12",
    "a3":"r13",
    "a4":"r14",
    "a5":"r15",
    "a6":"r16",
    "a7":"r17",
    "s2":"r18",
    "s3":"r19",
    "s4":"r20",
    "s5":"r21",
    "s6":"r22",
    "s7":"r23",
    "s8":"r24",
    "s9":"r25",
    "s10":"r26",
    "s11":"r27",
    "t3":"r28",
    "t4":"r29",
    "t5":"r30",
    "t6":"r31",
    "mtvec":"mtvec",
    "pmpaddr0":"pmpaddr0",
    "pmpcfg0":"pmpcfg0",
    "mstatus":"mstatus",
    "mepc":"mepc",
    "mcause":"mcause",
}


#Reading input file into buffer
if(simulator=="spike") :
    trap=0
    list=file_content.split('core   0: ')           #split based on core 0
    for i in list:
        i=re.sub(r'\n', ' ', i)                     #combine lines
        i=re.sub(r'x (\d{1})',r'x\1', i)            #fix brain dead spike print for regs
        i=re.sub(r'^0x0000000000001(.*)',r'', i)    #remove spike boot rom
        if(bool(re.search('trap_user_ecall',i))):#filter out everything after ecall 
           trap=1
        #filter empty instructions
        if((bool(re.search('0x',i))) & (trap==0)):
            fields=i.split()                     
            pc=int(fields[0],16)
            opcode=fields[1]
            asm=fields[2]
            #for j in fields:
            #    print (j)
            if(re.search('0x',fields[-2])):
                memaddr="--"
                memdata="--"
                reg="--"
                regdata="--"
            elif(re.search('mem',i)):
                memaddr=fields[-2]
                memdata=fields[-1]
                reg="--"
                regdata="--" 
            else:
                reg="x{0:02}".format(int(re.sub(r'x',r'', fields[-2])))
                regdata=fields[-1]
                memaddr="--"
                memdata="--"
            #Remove offsets
            if(pc>=offset):
                pc=pc-offset
            #List of entires
            flist=["0x{0:08x}".format(pc),
                   opcode,
                   "{:<8}".format(asm),
                   "{:<3}".format(reg),
                   "{:<10}".format(regdata),
                   "{:<10}".format(memaddr),
                   "{:<10}".format(memdata)]
            outputstring='  ,  '.join(flist)
            fileout.write(outputstring + "\n")
fileout.close()

